import { NextResponse } from "next/server";
import navigationsModule from '@/modules/navigation'
import buildNavigationTree from '@/utils/buildNavigationTree'
import flattenNavigationTree from '@/utils/flattenNavigationTree'
import pool from '@/lib/db';

export async function GET(request) {
  const data = await navigationsModule.get();
  if (!data) { return NextResponse.json({ code: 1, message: "Error" }); }
  return NextResponse.json({ code: 0, message: "Success", data: buildNavigationTree(data), originData: data });
}

export async function POST(request) {
  const codeMap = { 0: "保存成功", 1: '名称和URL都不能为空', 2: "保存失败", 3: "服务器错误" };
  const data = flattenNavigationTree(await request.json());
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    const newIds = data.map(item => item.id);
    const localIds = (await navigationsModule.get(connection)).map(item => item.id);
    const deleteIds = localIds.filter(id => !newIds.includes(id));
    if (deleteIds.length > 0) {
      const deleted = await navigationsModule.deleteById(deleteIds, connection);
      if (!deleted) {
        await connection.rollback();
        return NextResponse.json({ code: 2, codeMap, message: "Save failed" });
      }
    }
    for (const item of data) {
      const { id, status = 0, name, description, url, icon, position, sort, parent_id } = item
      if (!name || !url) {
        await connection.rollback();
        return NextResponse.json({ code: 1, codeMap, message: "Name and URL cannot be empty" });
      }
      const existing = await navigationsModule.getById(id, connection);
      if (existing) {
        const updated = await navigationsModule.update({ id, status, name, description, url, icon, position, sort, parent_id }, connection);
        if (!updated) {
          await connection.rollback();
          return NextResponse.json({ code: 2, codeMap, message: "Save failed" });
        }
      } else {
        const inserted = await navigationsModule.add({status, name, description, url, icon, position, sort, parent_id }, connection);
        if (!inserted) {
          await connection.rollback();
          return NextResponse.json({ code: 2, codeMap, message: "Save failed" });
        }
      }
    }
    await connection.commit();
    return NextResponse.json({ code: 0, codeMap, message: "Success" });
  } catch (error) {
    console.log(error);
    await connection.rollback();
    return NextResponse.json({ code: 3, codeMap, message: "Server error" });
  } finally {
    connection.release();
  }
}